package cn.itsource.user.service.impl;

import cn.itsource.basic.basic.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.dto.EmailDto;
import cn.itsource.user.dto.UserDto;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String inputPhoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        //校验是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(inputPhoneCode)
                                       || StringUtils.isEmpty(password)
                                       || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("所填信息不能为空");
        }

        //校验密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("前后密码不一致");
        }

        //校验手机验证码是否正确，是否过期
        Object redisPhoneCode = redisTemplate.opsForValue().get("register:" + phone);
        //验证是否过期
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码过期，请重新获取!!!");
        }
        //验证是否正确
        if(!inputPhoneCode.equals(redisPhoneCode.toString().split(":")[0])){  // code:时间戳
            throw new BusinessException("手机验证码错误!!!");
        }

        //添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //添加loininfo的信息，并且生成自增id
        logininfoMapper.add(logininfo);
        //再将自增id设置到user中，并且添加到user表
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private Logininfo user2Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        ///按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        //底层原理为getter，setter方法实现
        BeanUtils.copyProperties(user,logininfo);
        //验证码注册
        logininfo.setType(1);
        //手机验证码在注册成功过后就能够使用了
        logininfo.setDisable(true);
        return logininfo;
    }

    private User userDto2User(UserDto userDto){
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //加密加盐
        //生成随机盐值(32位)
        String salt = StrUtils.getComplexRandomString(32);
        //用md5技术加密
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    @Override
    public void emailRegister(EmailDto emailDto) {
        String email = emailDto.getEmail();
        String password = emailDto.getPassword();
        String passwordRepeat = emailDto.getPasswordRepeat();
        //校验是否为空
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                                       || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("所填信息不能为空");
        }

        //校验密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("前后密码不一致");
        }

        //添加到数据库
        User user = emailDto2User(emailDto);
        Logininfo logininfo = email2Logininfo(user);
        //添加loininfo的信息，并且生成自增id
        logininfoMapper.add(logininfo);
        //再将自增id设置到user中，并且添加到user表
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private Logininfo email2Logininfo(User user){
        Logininfo logininfo = new Logininfo();
        ///按照属性同名原则进行属性拷贝【username，email，phone，salt，password】
        //底层原理为getter，setter方法实现
        BeanUtils.copyProperties(user,logininfo);
        //验证码注册
        logininfo.setType(1);
        //手机验证码在注册成功过后就能够使用了
        logininfo.setDisable(true);
        return logininfo;
    }

    private User emailDto2User(EmailDto emailDto){
        User user = new User();
        user.setUsername(emailDto.getEmail());
        user.setEmail(emailDto.getEmail());
        //加密加盐
        //生成随机盐值(32位)
        String salt = StrUtils.getComplexRandomString(32);
        //用md5技术加密
        String md5Pwd = Md5Utils.encrypByMd5(emailDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    @Override
    @Transactional
    public void update(User user) {
        //用strUtils工具类进行加盐
        String salt = StrUtils.getComplexRandomString(32);
        //用md5技术进行加密
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //根据id找到之前的用户信息
        User oldUser = userMapper.findById(user.getId());

        //修改之前的用户信息
        user.setLogininfoId(oldUser.getLogininfoId());
        super.update(user);

        //找之前的用户信息所关联的登陆信息，并作出修改
        Logininfo oldLogininfo = logininfoMapper.findById(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        //先删除用户信息，再对其登录信息进行删除
        User user = userMapper.findById(id);
        super.delete(id);
        logininfoMapper.delete(user.getLogininfoId());
    }
}
